import 'package:base_flutter/base_flutter.dart';
import 'package:dart_sm/dart_sm.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/init_page/init_page.dart';
import 'package:ls_work/init_page/webview_page.dart';
import 'package:ls_work/login/mobile_check_login_widget.dart';
import 'package:ls_work/mvp/base_page_state.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/config_url_response.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/routers/fluro_navigator.dart';
import 'package:ls_work/routers/routers.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/native_toast.dart';
import 'package:ls_work/util/request_url_utils.dart';
import 'package:ls_work/widgets/app_bar.dart';
import 'package:flutterlifecyclehooks/flutterlifecyclehooks.dart';

import 'package:ls_work/widgets/load_image.dart';
import 'package:ls_work/widgets/text_field.dart';
import 'package:native_id/native_id.dart';

import '../../keyboard/secure_keyboard_type.dart';
import '../../keyboard/with_secure_keyboard.dart';
import '../../util/flat_button.dart';
import '../../util/show_policy_dialog.dart';
import '../presenter/user_presenter.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import '../user_permission_data.dart';
import './user_manager.dart';

/// design/1注册登录/index.html
class LoginPage extends StatefulWidget {
  String error;

  LoginPage({this.error = ""});

  @override
  LoginPageState createState() => LoginPageState();
}

class LoginPageState extends BasePageState<LoginPage, UserPagePresenter>
    with LifecycleMixin {
  final _secureKeyboardController = SecureKeyboardController();

  //定义一个controller
  TextEditingController _nameController = TextEditingController();
  TextEditingController _pddController = TextEditingController();
  TextEditingController _verifyController = TextEditingController();
  TextEditingController _codeController =
      TextEditingController(text: RequestUrlUtils.code);
  final FocusNode _nodeText0 = FocusNode();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();

  // KeyboardActionsConfig _config;
  bool _isClick = false;
  bool _isMindUserName = true; //是否记住账号
  ConfigUrlResponse? orgData;
  static bool _showError = false;

  var hasAgree = false;



  @override
  void initState() {
    super.initState();

    NativeUtils.setSecureScreen(true);
    WidgetsBinding.instance.addPostFrameCallback((duration) {
      if(BuildConfig.isDebug){
        DevConfig.instance.canGetNetRequest = true;
        DevConfig.instance.addNetFloating(context);
      }
      // NativeUtils.checkRootOrJailbreak().then((value) {
      //   if (value) {
      //     showHasRootDialog(context);
      //   }
      //   print("value");
      // });
    });
    if (widget.error.isNotEmpty && !_showError) {
      _showError = true;
      Future.delayed(Duration(milliseconds: 200), () {
        showCupertinoDialog(
            context: context,
            builder: (context) {
              return CupertinoAlertDialog(
                content: CommonText(widget.error),
                actions: [
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: CommonText('确定',
                          textSize: 15, textColor: Colours.app_main))
                ],
              );
            });
      });
    }

    //监听输入改变
    _nameController.addListener(_verify);
    // _pddController.addListener(_verify);
    setUrl();
    _codeController.addListener(() {
      setUrl();
    });
    // _config = Utils.getKeyboardActionsConfig([_nodeText1, _nodeText2]);

    if (Constant.inProduction == false) {
      ///测试服
      _nameController.text = '18869978285';
      _pddController.text = 'Szky#2025&1';
      // _nameController.text = UserManager.account;
      // _pddController.text = UserManager.pdd;
      ////正式服
      // _nameController.text = 'zhouyingshuang';
      // _passwordController.text = 'abcd09151687';
    } else {
      // _nameController.text =
      //     FlutterStars.SpUtil.getString(Constant.login_userName) ?? '';
      _nameController.text = UserManager.account;
      // _pddController.text = UserManager.pdd;
    }
  }

  Future<void> setUrl() async {
    var code = _codeController.text;
    if (code.isNullOrEmpty()) {
      return;
    }
    var data = await RequestUrlUtils.findUrl(code);
    setState(() {
      orgData = data;
    });
    if (orgData != null) {
      getVerifyCode();
    }
  }

  void _verify() {
    String name = _nameController.text;
    String pdd = _pddController.text;
    bool isClick = true;
    if (name.isEmpty) {
      isClick = false;
    }
    if (pdd.isEmpty) {
      isClick = false;
    }

    /// 状态不一样在刷新，避免重复不必要的setState
    if (isClick != _isClick) {
      setState(() {
        _isClick = isClick;
      });
    }
  }

  Future<void> _login() async {
    if (_codeController.text.isNullOrEmpty()) {
      showToast("请输入项目编号");
      return;
    }

    if (_nameController.text.isEmpty) {
      showToast("请输入账号");
      return;
    }
    if (_pddController.text.isEmpty) {
      showToast("请输入密码");
      return;
    }
    if (_verifyController.text.isEmpty) {
      showToast("请输入验证码");
      return;
    }

    // presenter.login(username: '13900000000',password: '000000',isShowDialog: true);
    // POST 请求
    var psd = SM2.encrypt(_pddController.text, pck!);
    var uniCode = await NativeId().getId();
    showProgress();
    var params = {
      "username": _nameController.text,
      "password": psd,
      "cryptoType": "sm2",
      "needMenu": true,
      "needAppMenu": true,
      "code": _verifyController.text,
      "deviceCode": uniCode
    };
    HttpGo.instance
        .postData(HttpApi.login,
            data: params, options: PostRequest.urlencodedHeader)
        .then((map) async {
      closeProgress();
      if (map["code"].toString() == "0") {
        showToast('登录成功');
        Map<String, dynamic> d = map['data'];
        d["password"] = _pddController.text;
        d['account'] = _nameController.text;
        UserManager.instance.login(d);
        UserPermissionData.saveMenus(d['menus']);
        // if (_isMindUserName) {
        //   FlutterStars.SpUtil.putString(
        //       Constant.login_userName, _nameController.text);
        // } else {
        //   FlutterStars.SpUtil.remove(Constant.login_userName);
        // }
        NavigatorUtils.push(context, Routes.inithome, clearStack: true);
      } else {
        closeProgress();
        if(map['data']?['checkDeviceCode']!=null){
          ///todo:验证码登录
          var result = await showMobileCheckDialog(context: context, msg: map['msg'], mobile: map['data']?['mobile']??'',password: psd,account: _nameController.text);
          if(result==true){
            NavigatorUtils.push(context, Routes.inithome, clearStack: true);
          }
        }else{
          getVerifyCode();
          showToast(map["msg"]);
        }
      }
    }).catchError((e) {
      closeProgress();
      getVerifyCode();
      showToast(NetErrorUtils.getNetError(e));
    });
  }

  @override
  Widget build(BuildContext context) {
    return WithSecureKeyboard(
        controller: _secureKeyboardController,
        child: Scaffold(
            appBar: MyAppBar(
              isBack: false,
            ),
            body: defaultTargetPlatform == TargetPlatform.iOS
                ? SingleChildScrollView(
                    // config: _config,
                    child: _buildBody(),
                  )
                : SingleChildScrollView(
                    child: _buildBody(),
                  )));
  }

  ///忘记密码弹窗
  _show() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('忘记密码'),
        titleTextStyle: TextStyles.textBoldDark18,
        content: Text(('请联系管理员进行更改')),
        contentTextStyle: TextStyles.textGray14,
        actions: <Widget>[
          FlatsButton(
            child: new Text("确定"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }

  _buildBody() {
    return Padding(
      padding: EdgeInsets.only(left: 30.0, right: 30.0, top: 15.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Gaps.vGap15,
          Container(
            width: double.infinity,
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 15),
            // child: CommonText("数字康养",fontWeight: FontWeight.bold,textSize: 34,textColor: Color(0xff333333))
            child: GlobalConfigs.loginLogo.isNullOrEmpty()
                ? CommonText('数字康养平台',
                        textSize: 30,
                        fontWeight: FontWeight.bold,
                        textColor: Colors.orange)
                    .addToContainer(height: 80)
                : LoadAssetImage(
                    GlobalConfigs.loginLogo!,
                    height: 80,
                  ),
          ),
          Gaps.vGap50,
          MyTextField(
            key: const Key('code'),
            focusNode: _nodeText0,
            controller: _codeController,
            keyboardType: TextInputType.text,
            hintText: "项目编号",
          ),
          Gaps.vGap8,
          MyTextField(
            key: const Key('phone'),
            focusNode: _nodeText1,
            controller: _nameController,
            keyboardType: TextInputType.text,
            hintText: "账号",
          ),
          Gaps.vGap8,
          // TextFormField(
          //   controller: _pddController,
          //   focusNode: _nodeText2,
          //   // We recommended to set false to prevent the software keyboard from opening.
          //   enableInteractiveSelection: false,
          //   obscureText: true,
          //   onTap: () {
          //     _secureKeyboardController.show(
          //       type: SecureKeyboardType.ALPHA_NUMERIC,
          //       focusNode: _nodeText2,
          //       initText: _pddController.text,
          //       hintText: 'password',
          //       // Use onCharCodesChanged to have text entered in real time.
          //       onCharCodesChanged: (List<int> charCodes) {
          //         _pddController.text = String.fromCharCodes(charCodes);
          //       },
          //     );
          //   },
          // ),
          MyTextField(
            keyName: 'password',
            focusNode: _nodeText2,
            // config: _config,
            isInputPwd: true,
            enableInteractiveSelection: false,
            controller: _pddController,
            hintText: "密码",
            onTap: () {
              _secureKeyboardController.show(
                  type: SecureKeyboardType.ALPHA_NUMERIC,
                  focusNode: _nodeText2,
                  initText: _pddController.text,
                  hintText: 'password',
                  onCharCodesChanged: (List<int> charCodes) {
                    _pddController.text = String.fromCharCodes(charCodes);
                  },
                  onCloseKeyPressed: () {});
            },
          ),
          Gaps.vGap10,

          Row(
            children: [
              Expanded(
                  child: MyTextField(
                key: const Key('verifyCode'),
                keyName: 'verifyCode',
                focusNode: _nodeText3,
                controller: _verifyController,
                hintText: "验证码",
              )),
              if (!verifyCode.isNullOrEmpty())
                Image.memory(base64Decode(verifyCode!)).onTap(() {
                  getVerifyCode();
                })
              else
                CommonText('获取验证码', textColor: Colours.app_main)
                    .addToContainer(
                        padding:
                            EdgeInsets.symmetric(horizontal: 8, vertical: 4))
                    .onTap(() {
                  getVerifyCode();
                })
            ],
          ),
          Container(
            height: 40.0,
            width: double.infinity,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: _show,
                    child: const Text(
                      '忘记密码？',
                      style: TextStyles.textGray12,
                    ),
                  ),
                ),
                // Checkbox(
                //   activeColor: Colours.app_main,
                //   value: _isMindUserName,
                //   onChanged: (value) {
                //     setState(() {
                //       _isMindUserName = value!;
                //     });
                //   },
                // ),
                // Text(
                //   '记住账号',
                //   style: TextStyles.textGray12,
                // ),
              ],
            ),
          ),
          Gaps.vGap15,
          if (GlobalConfigs.needShowPolicy)
            Row(
              children: [
                Icon(
                  hasAgree ? Icons.check_circle : Icons.radio_button_off,
                  size: 18,
                  color: hasAgree ? Colours.app_main : Colors.grey,
                ),
                const SizedBox(
                  width: 5,
                ),
                Text.rich(TextSpan(
                  children: [
                    TextSpan(
                        text: '我已阅读并同意',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colours.gray_99,
                        )),
                    TextSpan(
                        text: '《服务协议》',
                        style: TextStyle(color: Colours.app_main, fontSize: 14),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Go().push(WebViewPage(
                                title: '服务协议', url: GlobalConfigs.agreenment));
                            // openWeb(url: Apis.agreement,title: '服务协议');
                          }),
                    TextSpan(
                        text: '和',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colours.gray_99,
                        )),
                    TextSpan(
                        text: '《隐私政策》',
                        style: TextStyle(color: Colours.app_main, fontSize: 14),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            Go().push(WebViewPage(
                                title: '隐私政策', url: GlobalConfigs.privacy));
                          }),
                  ],
                )).setWeight(1),
              ],
            ).onTap(() {
              setState(() {
                hasAgree = !hasAgree;
              });
            }),
          Gaps.vGap15,
          Gaps.vGap15,
          TextButton(
            style: TextButton.styleFrom(
              padding: EdgeInsets.zero,
              overlayColor: Colors.transparent,
            ),
            onPressed: () {
              if (hasAgree || !GlobalConfigs.needShowPolicy) {
                _login();
              } else {
                if (_codeController.text.isEmpty) {
                  showToast("请输入项目编码");
                  return;
                }
                if (_nameController.text.isEmpty) {
                  showToast("请输入账号");
                  return;
                }
                if (_pddController.text.isEmpty) {
                  showToast("请输入密码");
                  return;
                }

                if (_verifyController.text.isEmpty) {
                  showToast("请输入验证码");
                  return;
                }
                showPolicyDialog(context, onApplyClick: () {
                  Go().pop();
                  setState(() {
                    hasAgree = true;
                  });
                  _login();
                }, onCancelClick: () {
                  Go().pop();
                });
              }
            },
            child: Image.asset(
              "assets/login_btn.png",
              width: double.infinity,
              fit: BoxFit.fitWidth,
            ),
          ),
          Gaps.vGap16,
          Gaps.vGap16,
          // Container().setWeight(1),
          CommonText(orgData == null ? "" : orgData?.name ?? "")
              .addToContainer(alignment: Alignment.center)
        ],
      ),
    );
  }

  @override
  void dispose() {
    NativeUtils.setSecureScreen(false);
    _pddController.dispose();
    _nameController.dispose();
    _verifyController.dispose();
    _codeController.dispose();
    super.dispose();
  }

  @override
  UserPagePresenter createPresenter() {
    return UserPagePresenter();
  }

  ///sm2公钥
  String? pck;

  ///sm2私钥
  String? prik;

  ///验证码
  String? verifyCode;

  ///获取验证码
  Future<void> getVerifyCode() async {
    try {
      var data = await HttpGo.instance.dio!.post("${HttpApi.baseUrl}checkCode/getCheckCode",
          options: Options(
              contentType: Headers.jsonContentType,
              responseType: ResponseType.plain));
      var cookie = initCookies(data);
      if (cookie.isNotEmpty) {
        var map = {"cookie": cookie};
        UserManager.instance.saveCookie(map);
      }

      prik = data!.toString().substring(35, 35 + 64);
      pck = data.toString().substring(35 + 64, 35 + 64 + 130);
      if (BuildConfig.isDebug) {
        print("pck===>${pck}");
        print("prik===>${prik}");
      }
      var imageData = data.toString().substring(0, 35) +
          data.toString().substring(35 + 64 + 130);
      var image = SM2.decrypt(imageData, prik!);

      setState(() {
        verifyCode = jsonDecode(image)['data'];
      });

      UserManager.instance.saveItemKey(prik!);
    } catch (e) {
      // print("error===>${e}");
      showToast(e.toNetError());
    }
  }

  @override
  void onAppHide() {
    NativeUtils.showToast("数字康养进入后台运行");
    _pddController.text = "";
    super.onAppHide();
  }
}

void showHasRootDialog(BuildContext context) {
  showDialog(
      context: context,
      builder: (context) {
        return PopScope(child: Dialog(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Gaps.vGap12,
              Text(
                '设备已被ROOT',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              Gaps.vGap12,
              Text(
                '检测到您的设备已被ROOT，存在隐私信息泄漏和被非法攻击等风险！',
                style: TextStyle(fontSize: 14, color: Colors.grey,),
                textAlign: TextAlign.center,
              ),
              Gaps.vGap12,
              Gaps.dividerLine,
              TextButton(
                onPressed: () {
                  hasAgreeRoot = true;
                  Navigator.pop(context);
                },
                child: Text(
                  '我已明白此风险，依然继续',
                  style: TextStyle(fontSize: 16, color: Colors.blue),

                ),
              ),
            ],
          ).addToContainer(color: Colors.white,constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width*0.7,
          ),padding: EdgeInsets.symmetric(horizontal: 12)),
        ),canPop: false,onPopInvoked: (didPop){
          // if(!didPop){
          //   Go().pop();
          // }
        },);
      });
}
